package com.vectquant.lwwl_service01.service;

import com.vectquant.lwwl_service01.model.User;
import com.vectquant.lwwl_service01.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 用户服务类，处理用户相关的业务逻辑
 */

@Service
public class UserService {
//    @Autowired
    private final UserRepository userRepository;
    private final WechatService wechatService;
    public UserService(UserRepository userRepository,WechatService wechatService){
        this.userRepository = userRepository;
        this.wechatService = wechatService;
    }

    /**
     * 通过code登录或注册新用户
     * @param code微信登陆code
     * @param encryptedData 加密数据
     * @param iv初始向量
     * @return 用户对象
     * @throws RuntimeException 当用户名或邮箱已存在时抛出异常
     */

    public User loginOrRegister(String code,String phoneCode){
//       获取openid和session_key
        Map<String,String> wechatResult = wechatService.getOpenidByCode(code);
        String openid = wechatResult.get("openid");
        String sessionKey = wechatResult.get("session_key");
//        查找用户是否已存在
        Optional<User> userOptional = userRepository.findByOpenid(openid);
        User user;

       if (userOptional.isPresent()){
//           用户已经存在，更新最后登录时间
           user = userOptional.get();
           user.setLastLoginTime(new Date());
       }else {
//           用户不存在，创建用户
           user = new User();
           user.setOpenid(openid);
           user.setCreatTime(new Date());
           user.setLastLoginTime(new Date());
       }
//       解密手机号并保存
        if (phoneCode != null && !phoneCode.isEmpty()){
            String phone = wechatService.getPhoneNumberByCode(phoneCode);
            user.setPhone(phone);
        }
//        保存用户信息
        return userRepository.save(user);
    }
    /**
     * @param phoneCode 获取手机号的临时凭证
     * @return 用户对象
     */
    public String getPhoneNumber(String phoneCode){
        return wechatService.getPhoneNumberByCode(phoneCode);
    }
    /**
     * 根据openid获取用户信息
     * @param openid 微信openid
     * @return 用户对象
     */

    public User getUserByOpenid(String openid){
        return userRepository.findByOpenid(openid)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
    }
    /**
     * 更新用户信息
     * @param user用户对象
     * @return 更新后的用户对象
     */
    public User updateUser(User user){
        return userRepository.save(user);
    }
}
